import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:tihai/entity/problem.dart';
import 'package:tihai/entity/result.dart';
import 'package:tihai/util/network.dart';
import 'package:tihai/util/storage.dart';

import '../../entity/type.dart';

class ProblemPage extends StatefulWidget {
  const ProblemPage({Key? key}) : super(key: key);

  @override
  State<ProblemPage> createState() => _ProblemPageState();
}

class _ProblemPageState extends State<ProblemPage> {
  var titleText = TextEditingController();
  var choiceAText = TextEditingController();
  var choiceBText = TextEditingController();
  var choiceCText = TextEditingController();
  var choiceDText = TextEditingController();
  var detailText = TextEditingController();
  var scoreText = TextEditingController();

  List<dynamic> listItem = [];
  int currentItem = 0;
  dynamic currentAnswer = "A";

  @override
  void initState() {
    super.initState();
    getItemData();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: const Text("返回"),
        ),
        appBar: AppBar(
          title: const Text("提交题目"),
        ),
        body: Container(
          decoration: const BoxDecoration(color: Colors.white70),
          child: Column(
            children: [
              Expanded(
                flex: 1,
                child: TextField(
                  controller: titleText,
                  textInputAction: TextInputAction.next,
                  decoration: const InputDecoration(
                      hintText: "请输入标题", border: OutlineInputBorder()),
                ),
              ),
              Expanded(
                  flex: 1,
                  child: DropdownButton<dynamic>(
                    hint: const Text("请选择分区"),
                    items: getItem(),
                    value: currentItem,
                    onChanged: (value) {
                      setState(() {
                        currentItem = value;
                      });
                    },
                  )),
              Expanded(
                flex: 1,
                child: TextField(
                  controller: scoreText,
                  textInputAction: TextInputAction.next,
                  decoration: const InputDecoration(
                      hintText: "请输入奖励分数", border: OutlineInputBorder()),
                  inputFormatters: [
                    FilteringTextInputFormatter.digitsOnly
                  ],
                ),
              ),
              Expanded(
                flex: 1,
                child: Row(
                  children: [
                    Expanded(flex: 3, child: TextField(
                      controller: choiceAText,
                      textInputAction: TextInputAction.next,
                      decoration: const InputDecoration(
                          hintText: "请输入选项A", border: OutlineInputBorder()),
                    ),),
                    Expanded(flex: 1, child: ElevatedButton(
                      onPressed: (){
                        getRandomChoice("A");
                      },
                      child: const Text("随机"),
                    )),
                  ],
                )
              ),
              Expanded(
                  flex: 1,
                  child: Row(
                    children: [
                      Expanded(flex: 3, child: TextField(
                        controller: choiceBText,
                        textInputAction: TextInputAction.next,
                        decoration: const InputDecoration(
                            hintText: "请输入选项B", border: OutlineInputBorder()),
                      ),),
                      Expanded(flex: 1, child: ElevatedButton(
                        onPressed: (){
                          getRandomChoice("B");
                        },
                        child: const Text("随机"),
                      )),
                    ],
                  )
              ),
              Expanded(
                  flex: 1,
                  child: Row(
                    children: [
                      Expanded(flex: 3, child: TextField(
                        controller: choiceCText,
                        textInputAction: TextInputAction.next,
                        decoration: const InputDecoration(
                            hintText: "请输入选项C", border: OutlineInputBorder()),
                      ),),
                      Expanded(flex: 1, child: ElevatedButton(
                        onPressed: (){
                          getRandomChoice("C");
                        },
                        child: const Text("随机"),
                      )),
                    ],
                  )
              ),
              Expanded(
                  flex: 1,
                  child: Row(
                    children: [
                      Expanded(flex: 3, child: TextField(
                        controller: choiceDText,
                        textInputAction: TextInputAction.next,
                        decoration: const InputDecoration(
                            hintText: "请输入选项D", border: OutlineInputBorder()),
                      ),),
                      Expanded(flex: 1, child: ElevatedButton(
                        onPressed: (){
                          getRandomChoice("D");
                        },
                        child: const Text("随机"),
                      )),
                    ],
                  )
              ),
              Expanded(
                  flex: 1,
                  child: DropdownButton<dynamic>(
                    hint: const Text("请输入答案(ABCD)"),
                    items: getAnswerItem(),
                    value: currentAnswer,
                    onChanged: (value) {
                      setState(() {
                        currentAnswer = value;
                      });
                    },
                  )),
              Expanded(
                flex: 1,
                child: TextField(
                  controller: detailText,
                  textInputAction: TextInputAction.next,
                  decoration: const InputDecoration(
                      hintText: "请输入解析", border: OutlineInputBorder()),
                ),
              ),
              Expanded(
                flex: 1,
                child: ElevatedButton(
                    onPressed: () {
                      submit();
                      Navigator.pop(context);
                    },
                    child: const Text("提交")),
              ),
            ],
          ),
        ),
      ),
    );
  }

  submit() async {
    Map<String, dynamic> data = {};
    data["userId"] = await Storage.getString("userId");
    // data["typeId"] = ModalRoute.of(context)!.settings.arguments;
    data["title"] = titleText.text;
    data["typeId"] = currentItem;
    data["score"] = scoreText.text;
    data["choiceA"] = choiceAText.text;
    data["choiceB"] = choiceBText.text;
    data["choiceC"] = choiceCText.text;
    data["choiceD"] = choiceDText.text;
    data["answer"] = currentAnswer;
    data["detail"] = detailText.text;
    Result result = await postAPI(API.createProblem, data);
  }

  getItem() {
    return listItem
        .map((e) => DropdownMenuItem(value: e.id, child: Text(e.name)))
        .toList();
  }

  getItemData() async {

    listItem = await getListAPI(TypeBean(), API.selectTypeList, {});
    setState(() {
      currentItem = listItem[0].id;
    });
  }

  getAnswerItem(){
    return const [
      DropdownMenuItem(value: "A",child: Text("A"),),
      DropdownMenuItem(value: "B",child: Text("B"),),
      DropdownMenuItem(value: "C",child: Text("C"),),
      DropdownMenuItem(value: "D",child: Text("D"),),
    ];
  }

  getRandomChoice(str) async {
    ProblemBean problemBean = await getAPI(ProblemBean(), API.randomChoice, {});
    String result = problemBean.answer;
    setState(() {
      switch(str){
        case "A":
          choiceAText.text = result;
          break;
        case "B":
          choiceBText.text = result;
          break;
        case "C":
          choiceCText.text = result;
          break;
        case "D":
          choiceDText.text = result;
          break;
      }
    });
  }
}
